#!/usr/bin/env bash

#get this script real directory
SOURCE="$0"
while [ -h "$SOURCE"  ]; do # resolve $SOURCE until the file is no longer a symlink
    this_script_dir="$( cd -P "$( dirname "$SOURCE"  )" && pwd  )"
    SOURCE="$(readlink "$SOURCE")"
    # if $SOURCE was a relative symlink, 
    #we need to resolve it relative to the path 
    #where the symlink file was located
    [[ $SOURCE != /*  ]] && SOURCE="$this_script_dir/$SOURCE"
done
this_script_dir="$( cd -P "$( dirname "$SOURCE"  )" && pwd  )"

log_level=${log_level:=info}
assist_dir=${assist_dir:=$this_script_dir/assist}
source $assist_dir/global.sh

main()
{
    if [ "$(whoami)" != "root" ] ; then  
        vloge "please execute by user root." 
        return 1;
    fi

    local ip_old=""
    while [ true ] 
    do
        domain_ip=$(nslookup git.igcc.cc 223.5.5.5| tail -n 4 | grep Address)
        if [ $? -ne 0 ] ; then
            vlogw "nslooup run failed."
            sleep 600
            continue;
        fi

        domain_ip=${domain_ip##* }
        vlogi "current domain_ip is:$domain_ip"

        if [ -n "$domain_ip" ] ; then
            if [ -z "$ip_old" ] ; then
                ip_old=$domain_ip
            else
                if [ "$ip_old" != "$domain_ip" ] ; then
                    ip_old=$domain_ip
                    nginx -s reload
                    vlogi "domain_ip changed, reload nginx."
                fi
            fi
        fi

        sleep 600
    done
    return 0;
}

main || exit 1 && exit 0

